import Api from '@/api';

let fileNameKey = +new Date();

export default {
  namespaced: true,
  state: {
    tokenData: null,
    expiried: true,
  },
  mutations: {
    setTokenData(state, payload) {
      state.tokenData = payload;
    },
    // key为文件名，使用之后需要更新，避免文件重名
    setFileNameKey(state, payload) {
      state.tokenData.key = payload;
    },
  },
  actions: {
    async getTokenData({ state, commit, dispatch }, payload) {
      const { tokenData: hasToken } = state;
      if (hasToken) {
        return hasToken;
      }
      const { data } = await Api.getQiNiuToken({
        scope: 'pub-med-casem',
        watermark: false,
        policy: {},
        ...payload,
      });
      if (data) {
        commit('setTokenData', data);
        dispatch('updateFileNameKey');
      }
      return data;
    },
    async refreshTokenData({ state, commit, dispatch }, payload) {
      const { data } = await Api.getQiNiuToken({
        scope: 'pub-med-casem',
        watermark: false,
        policy: {},
        ...payload,
      });
      if (data) {
        commit('setTokenData', data);
        dispatch('updateFileNameKey');
      }
      return data;
    },
    checkTokenData({ state, dispatch }) {
      if (state.expiried || !state.tokenData) {
        dispatch('getTokenData');
        return false;
      }
      return true;
    },
    updateFileNameKey({ commit }) {
      fileNameKey += 10;
      commit('setFileNameKey', fileNameKey);
    },
  },
};
